package com.zzgc.modules.service.impl;

import com.zzgc.common.dao.*;
import com.zzgc.common.entity.*;
import com.zzgc.modules.param.*;
import com.zzgc.modules.service.StudentArchivesService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 学生档案模板(StudentArchives)表服务实现类
 *
 * @author makejava
 * @since 2022-11-22 08:43:29
 */
@Service("studentArchivesService")
public class StudentArchivesServiceImpl implements StudentArchivesService {
    @Resource
    private StudentArchivesDao studentArchivesDao;
    @Resource
    private SchoolGradeDao schoolGradeDao;
    @Resource
    private SchoolGradeClassDao schoolGradeClassDao;
    @Resource
    private AuthUserDao authUserDao;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public StudentArchives queryById(Long id, String tableName) {
        return this.studentArchivesDao.queryById(id, tableName);
    }

    @Override
    public long count(StudentArchives studentArchives) {
        return this.studentArchivesDao.count(studentArchives);
    }

    /**
     * 分页查询, 导出到表格
     *
     * @param studentArchives 筛选条件
     * @return 查询结果
     */
    @Override
    public List<ExportArchivesTemplate> queryAllByLimitExport(StudentArchives studentArchives) {
        return this.studentArchivesDao.queryAllByLimitExport(studentArchives);
    }

    /**
     * 分页查询, 查询学生档案
     *
     * @param archivesParam 筛选条件
     * @return 查询结果
     */
    @Override
    public List<StudentArchivesParam> queryAllByLimitArchives(StudentArchivesParam archivesParam) {
        List<StudentArchivesParam> archivesParams = this.studentArchivesDao.queryAllByLimitArchives(archivesParam);
        long l = this.studentArchivesDao.queryAllByLimitArchivesCount(archivesParam);
        if (l == 0) {
            return new ArrayList<>();
        }
        archivesParams.get(0).setTotal(l);
        return archivesParams;
    }

    @Override
    public int maxFlag(String tableName) {
        Integer integer = this.studentArchivesDao.maxFlag(tableName);
        return integer == null ? 0 : integer;
    }

    @Override
    public int maxNumber(String tableName, String sYear) {
        Integer integer = this.studentArchivesDao.maxNumber(tableName, sYear);
        // 如果查询的是空的话, 就给个1
        return integer == null ? 1 : integer;
    }

    @Override
    public School queryAll(StudentArchives studentArchives) {
        return this.studentArchivesDao.queryAll(studentArchives);
    }

    /**
     *  合表查询,查询全部的学校档案
     */
    @Override
    public List<StudentArchivesParam> queryAllSchoolByLimitArchives(StudentArchivesParam archivesParam) {
        List<StudentArchivesParam> studentArchivesParams = this.studentArchivesDao.queryAllArchives(archivesParam);
        long count = this.studentArchivesDao.queryAllArchivesCount(archivesParam);
        if (count == 0){
            return new ArrayList<>();
        }
        studentArchivesParams.get(0).setTotal(count);
        return studentArchivesParams;
    }

    @Override
    public List<DataAnalysisParam> queryAllCountySchool(StudentArchivesParam archivesParam) {
        List<DataAnalysisParam> dataAnalysisParams = this.studentArchivesDao.queryAllCountySchool(archivesParam);
        long count = this.studentArchivesDao.queryAllArchivesCount(archivesParam);
        if (count == 0){
            return new ArrayList<>();
        }
        // 添加已测学校数量
        dataAnalysisParams.get(0).setInspect((int)count);
        return dataAnalysisParams;
    }

    /**
     * 分页查询
     *
     * @param studentArchives 筛选条件
     * @return 查询结果
     */
    @Override
    public List<StudentArchives> queryByPage(StudentArchives studentArchives) {
        List<StudentArchives> studentArchives1 = this.studentArchivesDao.queryAllByLimit(studentArchives);
        long count = this.studentArchivesDao.count(studentArchives);
        if (studentArchives1.size() == 0) {
            return new ArrayList<>();
        }
        studentArchives1.get(0).setTotal(count);
        return studentArchives1;
    }

    /**
     * 新增数据
     *
     * @param studentArchives 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public StudentArchives insert(Long userId, StudentArchives studentArchives) {
        Date date = new Date();
        // 查询用户
        AuthUser user = authUserDao.queryById(userId);
        // 查询部门
//        AuthDepart authDepart = authDepartDao.queryById(user.getADepartId());

        // 添加年级表, 判断年份年级是否重复
        SchoolGrade schoolGrade = new SchoolGrade();
        List<SchoolGrade> schoolGrades = schoolGradeDao.queryAllBy(user.getASchoolId(), studentArchives.getSGradeName(), studentArchives.getSYear());
        if (schoolGrades.size() == 1) {
            schoolGrade = schoolGrades.get(0);
        } else {
            // 学校id
            schoolGrade.setSCreateBy(user.getAName());
            schoolGrade.setSSchoolId(user.getASchoolId());
            schoolGrade.setSName(studentArchives.getSGradeName());
            schoolGrade.setSYear(studentArchives.getSYear());
            schoolGrade.setSCreateDate(date);
            schoolGradeDao.insert(schoolGrade);
        }

        // 添加班级表, 判断年级班级是否重复
        SchoolGradeClass schoolGradeClass = new SchoolGradeClass();
        List<SchoolGradeClass> schoolGradeClasses = schoolGradeClassDao.queryAllBy(user.getASchoolId(), studentArchives.getSClassName(), schoolGrade.getId());
        if (schoolGradeClasses.size() == 1) {
            schoolGradeClass = schoolGradeClasses.get(0);
        } else {
            // 学校id
            schoolGradeClass.setSSchoolId(user.getASchoolId());
            schoolGradeClass.setSCreateBy(user.getAName());
            schoolGradeClass.setSCreateDate(date);
            // 年级id
            schoolGradeClass.setSGradeId(schoolGrade.getId());
            schoolGradeClass.setSName(studentArchives.getSClassName());
            schoolGradeClassDao.insert(schoolGradeClass);
        }

        // 添加学生表
        // 添加表名archives_410104_4
//        studentArchives.setTableName("archives_" + authDepart.getARegionId() + "_" + user.getASchoolId());
        // 添加时间
        studentArchives.setSCreateDate(date);
        studentArchives.setSCreateBy(user.getAName());
        // 添加学校id
        studentArchives.setSSchoolId(user.getASchoolId());
        // 添加年级id
        studentArchives.setSGradeId(schoolGrade.getId());
        // 添加班级id
        studentArchives.setSClassId(schoolGradeClass.getId());
        this.studentArchivesDao.insert(studentArchives);
        return studentArchives;
    }

    /**
     * 修改数据
     *
     * @param studentArchives 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public StudentArchives update(Long userId, Long schoolId, StudentArchives studentArchives) {
        Date date = new Date();
        // 查询用户
        AuthUser user = authUserDao.queryById(userId);

        // 添加年级表, 判断年份年级是否重复
        SchoolGrade schoolGrade = new SchoolGrade();
        List<SchoolGrade> schoolGrades = schoolGradeDao.queryAllBy(schoolId, studentArchives.getSGradeName(), studentArchives.getSYear());
        if (schoolGrades.size() == 1) {
            schoolGrade = schoolGrades.get(0);
        } else {
            // 学校id
            schoolGrade.setSUpdateBy(user.getAName());
            schoolGrade.setSName(studentArchives.getSGradeName());
            schoolGrade.setSYear(studentArchives.getSYear());
            schoolGrade.setSUpdateDate(date);
            schoolGradeDao.insert(schoolGrade);
        }

        // 添加班级表, 判断班级是否重复
        SchoolGradeClass schoolGradeClass = new SchoolGradeClass();
        List<SchoolGradeClass> schoolGradeClasses = schoolGradeClassDao.queryAllBy(schoolId, studentArchives.getSClassName(), schoolGrade.getId());
        if (schoolGradeClasses.size() == 1) {
            schoolGradeClass = schoolGradeClasses.get(0);
        } else {
            // 学校id
            schoolGradeClass.setSUpdateBy(user.getAName());
            schoolGradeClass.setSUpdateDate(date);
            // 年级id
            schoolGradeClass.setSGradeId(schoolGrade.getId());
            schoolGradeClass.setSName(studentArchives.getSClassName());
            schoolGradeClassDao.insert(schoolGradeClass);
        }

        // 修改学生表
        // 修改时间
        studentArchives.setSUpdateDate(date);
        studentArchives.setSUpdateBy(user.getAName());
        // 修改年级id
        studentArchives.setSGradeId(schoolGrade.getId());
        // 添加班级id
        studentArchives.setSClassId(schoolGradeClass.getId());

        this.studentArchivesDao.update(studentArchives);
        return this.queryById(studentArchives.getId(), studentArchives.getTableName());
    }

    @Override
    public int updateDeleteFlags(List<StudentArchives> studentArchives) {
        return this.studentArchivesDao.updateDeleteFlags(studentArchives);
    }

    /**
     * 电子视力表提供数据
     *
     * @ClassName StudentArchivesServiceImpl
     * @Date 2022/12/7  10:06
     * @Version 1.0
     */
    @Override
    @Transactional
    public StudentArchives insertStudentArchives(int number, Student student, VisualParam visualParam) {
        Date date = new Date();
        StudentArchives archives = new StudentArchives();
        archives.setSStudentId(student.getId());
        archives.setSNumber(number);
        archives.setSOkMirror(student.getSOkMirror());
        archives.setTableName(student.getTableName());
        List<StudentArchives> studentArchives = studentArchivesDao.queryAllByLimit(archives);
        // 添加学生档案信息
        // 判断是否是带镜   0代表裸眼视力  1代表戴镜视力
        if (visualParam.getIsGlasses() == 0) {
            archives.setSRightEyeVisual(visualParam.getRight2().contains("<") ? "4.0" : visualParam.getRight2()); // 裸眼视力 右
            archives.setSLeftEyeVisual(visualParam.getLeft2().contains("<") ? "4.0" : visualParam.getLeft2()); // 裸眼视力 左
        } else {
            archives.setSRightGlassVisual(visualParam.getRight2().contains("<") ? "4.0" : visualParam.getRight2()); // 带镜 右
            archives.setSLeftGlassVisual(visualParam.getLeft2().contains("<") ? "4.0" : visualParam.getLeft2()); // 带镜 左
        }
        archives.setSCheckTime(date);

        // 如果存在就修改, 否则添加
        if (studentArchives.size() == 1) { // 修改
            archives.setId(studentArchives.get(0).getId());
            archives.setSUpdateBy("视力表");
            archives.setSUpdateDate(date);
            this.studentArchivesDao.update(archives);
            return studentArchivesDao.queryById(archives.getId(), student.getTableName());
        } else if (studentArchives.size() == 0) { // 添加
            archives.setSCreateBy("视力表");
            archives.setSCreateDate(date);
            archives.setSStudentUniqueId(student.getSStudentId());
            archives.setSSchoolName(student.getSSchoolName());
            archives.setSGradeName(student.getSGradeName());
            archives.setSClassName(student.getSClassName());
            archives.setSName(student.getSName());
            archives.setSStudentId(student.getId());
            archives.setSSex(student.getSSex());
            archives.setSBirthday(student.getSBirthday());
            archives.setSMobile(student.getSMobile());
            archives.setSIdCard(student.getSIdCard());
            archives.setSNumber(number);
            archives.setSYear(student.getSYear());
            this.studentArchivesDao.insert(archives);
            return studentArchivesDao.queryById(archives.getId(), archives.getTableName());
        }
        return null;
    }

    /**
     * 验光仪提供数据
     *
     * @ClassName StudentArchivesServiceImpl
     * @Date 2022/12/7  10:06
     * @Version 1.0
     */
    @Override
    @Transactional
    public StudentArchives insertStudentArchives(int number, Student student, RefractometerParam refractometerParam) {
        Date date = new Date();
        StudentArchives archives = new StudentArchives();
        archives.setSStudentId(student.getId());
        archives.setSStudentUniqueId(student.getSStudentId());
        archives.setSNumber(number);
        archives.setSOkMirror(student.getSOkMirror());
        archives.setTableName(student.getTableName());
        List<StudentArchives> studentArchives = studentArchivesDao.queryAllByLimit(archives);
        // 添加学生档案信息
        archives.setSRightAxial(refractometerParam.getRight_a_avg()); // 右眼轴位
        archives.setSLeftAxial(refractometerParam.getLeft_a_avg()); // 左眼轴位
        archives.setSColumnRight(refractometerParam.getRight_c_avg()); // 右眼柱镜
        archives.setSColumnLeft(refractometerParam.getLeft_c_avg()); // 左眼柱镜
        archives.setSRightMirror(refractometerParam.getRight_s_avg()); // 右眼球镜
        archives.setSLeftMirror(refractometerParam.getLeft_s_avg()); // 左眼球镜
        archives.setSPupilDistance(refractometerParam.getPd()); // 瞳距
        // 右眼等效球镜  球镜 + 柱镜/2
        float r = Float.parseFloat(refractometerParam.getRight_c_avg());
        float l = Float.parseFloat(refractometerParam.getLeft_c_avg());
        archives.setSRightEquivalentMirror(String.format("%.2f", (Float.parseFloat(refractometerParam.getRight_s_avg()) + r / 2)));
        // 左眼等效球镜
        archives.setSLeftEquivalentMirror(String.format("%.2f", (Float.parseFloat(refractometerParam.getLeft_s_avg()) + l / 2)));
        DateFormat sdf = new SimpleDateFormat("yy/MM/dd HH:mm:ss", Locale.ENGLISH);
//        DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
        sdf.setLenient(false); // 关闭自动计算
        try {
            Date testTime = sdf.parse(refractometerParam.getDetection_day() + " " + refractometerParam.getDetection_time());
            archives.setSCheckTime(testTime); // 添加时间
        } catch (ParseException e) {
            archives.setSCheckTime(date);
        }
        // 如果存在就修改, 否则添加
        if (studentArchives.size() == 1) { // 修改
            archives.setId(studentArchives.get(0).getId());
            archives.setSUpdateBy("验光仪");
            archives.setSUpdateDate(date);
            this.studentArchivesDao.update(archives);
            return studentArchivesDao.queryById(archives.getId(), student.getTableName());
        } else if (studentArchives.size() == 0) { // 添加
            archives.setSCreateBy("验光仪");
            archives.setSCreateDate(date);
            archives.setSSchoolName(student.getSSchoolName());
            archives.setSGradeName(student.getSGradeName());
            archives.setSClassName(student.getSClassName());
            archives.setSName(student.getSName());
            archives.setSStudentId(student.getId());
            archives.setSSex(student.getSSex());
            archives.setSBirthday(student.getSBirthday());
            archives.setSMobile(student.getSMobile());
            archives.setSIdCard(student.getSIdCard());
            archives.setSNumber(number);
            archives.setSYear(student.getSYear());
            this.studentArchivesDao.insert(archives);
            return studentArchivesDao.queryById(archives.getId(), archives.getTableName());
        }
        return null;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id, String tableName) {
        StudentArchives studentArchives = queryById(id, tableName);
        // 判断是否有同班的学生如果没有删除班级
        StudentArchives studentArchives1 = new StudentArchives();
        studentArchives1.setTableName(tableName);
        studentArchives1.setSClassId(studentArchives.getSClassId());
        if (studentArchivesDao.count(studentArchives1) == 1) {
            schoolGradeClassDao.deleteById(studentArchives.getSClassId());
        }
        // 判断是否有同年级的学生如果没有删除年级
        StudentArchives studentArchives2 = new StudentArchives();
        studentArchives2.setTableName(tableName);
        studentArchives2.setSGradeId(studentArchives.getSGradeId());
        if (studentArchivesDao.count(studentArchives2) == 1) {
            schoolGradeDao.deleteById(studentArchives.getSGradeId());
        }
        return this.studentArchivesDao.deleteById(id, tableName) > 0;
    }
}
